import { getFaultDetails } from "@/api/equipment/analysis";

export default {
  name: "EquipmentAnalysis",
  data() {
    return {
      faultDetails: [],
      loading: false,
      deviceType: '',
      dateRange: [],
      chart: null
    };
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    initChart() {
      this.chart = this.$echarts.init(this.$refs.chart);
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    async getFaultDetails() {
      this.loading = true;
      try {
        const params = {
          startDate: this.dateRange[0],
          endDate: this.dateRange[1]
        };
        const response = await getFaultDetails(this.deviceType, params);
        if (response.code === 200) {
          this.faultDetails = response.data;
          this.updateChart();
        } else {
          this.$message.error(response.msg || '获取故障详情失败');
        }
      } catch (error) {
        console.error('获取故障详情失败:', error);
        this.$message.error('获取故障详情失败');
      } finally {
        this.loading = false;
      }
    },

    updateChart() {
      if (!this.faultDetails || this.faultDetails.length === 0) {
        this.$message.warning('暂无数据');
        return;
      }

      // 统计每种故障类型的数量
      const faultTypeCount = {};
      this.faultDetails.forEach(item => {
        if (!faultTypeCount[item.faultType]) {
          faultTypeCount[item.faultType] = 0;
        }
        faultTypeCount[item.faultType]++;
      });

      const chartData = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const data = params[0];
            return `${data.name}<br/>故障次数：${data.value}`;
          }
        },
        xAxis: {
          type: 'category',
          data: Object.keys(faultTypeCount),
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '故障次数'
        },
        series: [{
          data: Object.entries(faultTypeCount).map(([name, value]) => ({
            value: value,
            name: name
          })),
          type: 'bar',
          itemStyle: {
            color: '#409EFF'
          }
        }]
      };

      this.chart.setOption(chartData);
      
      // 添加点击事件
      this.chart.off('click');
      this.chart.on('click', (params) => {
        this.handleChartClick(params);
      });
    },

    handleChartClick(params) {
      const { name } = params;
      this.$router.push({
        path: '/equipment/analysis/detail',
        query: {
          deviceType: this.deviceType,
          faultType: name,
          startDate: this.dateRange[0],
          endDate: this.dateRange[1]
        }
      });
    },

    handleQuery() {
      if (!this.deviceType) {
        this.$message.warning('请选择设备类型');
        return;
      }
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$message.warning('请选择日期范围');
        return;
      }
      this.getFaultDetails();
    },

    downloadChart() {
      if (!this.chart) {
        this.$message.warning('暂无图表数据');
        return;
      }

      if (!this.deviceType) {
        this.$message.warning('请先选择设备类型并查询数据');
        return;
      }

      if (!this.faultDetails || this.faultDetails.length === 0) {
        this.$message.warning('暂无故障数据可下载');
        return;
      }
      
      // 获取当前时间作为文件名
      const now = new Date();
      const deviceTypeMap = {
        'STACKER': '堆垛机',
        'CONVEYOR': '输送机',
        'SHUTTLE': '穿梭车'
      };
      const deviceTypeName = deviceTypeMap[this.deviceType] || this.deviceType;
      const dateRangeStr = this.dateRange && this.dateRange.length === 2 
        ? `${this.dateRange[0]}_${this.dateRange[1]}`
        : '全部日期';
      
      const fileName = `设备故障分析_${deviceTypeName}_${dateRangeStr}.png`;
      
      try {
        // 获取图表图片的base64数据
        const imgData = this.chart.getDataURL({
          type: 'png',
          pixelRatio: 2,
          backgroundColor: '#fff'
        });
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = imgData;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.$message.success('图表下载成功');
      } catch (error) {
        console.error('下载图表失败:', error);
        this.$message.error('下载图表失败，请重试');
      }
    }
  }
};

<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>设备故障分析</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="downloadChart">
          下载图表
        </el-button>
      </div>
      
      <!-- 查询条件 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="设备类型">
          <el-select v-model="deviceType" placeholder="请选择设备类型">
            <el-option label="堆垛机" value="STACKER"></el-option>
            <el-option label="输送机" value="CONVEYOR"></el-option>
            <el-option label="穿梭车" value="SHUTTLE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="loading">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 图表 -->
      <div v-loading="loading" class="chart-container">
        <div ref="chart" style="width: 100%; height: 400px;"></div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.chart-container {
  margin-top: 20px;
}
</style> 